//
//  SRReader.m
//  SunriseReaderDemo
//
//  Created by 田宇 on 2024/11/26.
//  Copyright © 2024 Chenfan. All rights reserved.
//

#import "SRReaderController.h"
#import <dlfcn.h>


#define APILog @"api/sdk/sdklogs/recordSdkLog"

@interface SRReaderController () <SRIDCardReaderDelegate> {
    NSDateFormatter *_dateFormatter;
}
//森锐读卡器sdk
@property (strong, nonatomic) SRIDCardReader *reader;

@property (strong, nonatomic) CBCentralManager *manager;
//上游传进来的参数参数
@property (strong, nonatomic) NSMutableDictionary *parameter;
@end


@implementation SRReaderController

- (id)initWithReader:(SRIDCardReader *)reader manager:(nonnull CBCentralManager *)manager{
    if (self = [super init]) {
        _reader = reader;
        _reader.delegate = self;
        _manager = manager;
        _serverAddress = @"http://36.134.163.187:39600/npl-sdk-service";
        _logInfo = [[SRReaderLogInfo alloc] init];
        _logInfo.opImpl = @"SRReaderController";
        _dateFormatter = [[NSDateFormatter alloc] init];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSTimeZone *chinaTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
        [_dateFormatter setTimeZone:chinaTimeZone];
        
    }
    return self;
}

//设置服务器地址
-(void)setServer:(NSString *)serverAddress{
    _serverAddress = serverAddress;
}


//上游参数
//idCardNumber:idCardNumber,
//phoneNumber:phoneNumber,
//innerSysNo:innerSysNo,
//regionCode:regionCode,
//regionName:regionName,
//channelCode:channelCode,
//channelName:channelName,
//employeeId:employeeId,
//cardTypeCode:cardTypeCode,
//channelName:channelName,
//cardTypeName:cardTypeName
- (void)readIDCardWithPeripheral:(CBPeripheral *)peripheral parameters:(nonnull NSDictionary *)param{
    
    NSDate *date = [NSDate date];  // Current date and time
    
    NSString *formattedDate = [_dateFormatter stringFromDate:date];
    _startTime = formattedDate;
    
    self.parameter = [NSMutableDictionary dictionaryWithDictionary:param];
    //连接蓝牙设备
    int ret = [_reader connectPeripheral:peripheral withCBManager:_manager withTimeout:5];
    NSLog(@"ret:%d",ret);
    if (ret == 0) {
        //读卡15秒超时时间
        [_reader readIDCardByJson:15];
    }else{
        //处理蓝牙连接失败问题
        _opResultDetail = [NSString stringWithFormat:@"%d:设备连接失败", ret];
        _resultTypeCode = [NSString stringWithFormat:@"%ld",(long)ret];
        _resultTypeName = @"设备连接失败";
        _resultTypeDetail = @"蓝牙设备连接失败";
        NSDate *date = [NSDate date];  // Current date and time
        NSString *formattedDate = [_dateFormatter stringFromDate:date];
        _endTime = formattedDate;
        [self handlerLogInfo];
        
        if ([self.delegate respondsToSelector:@selector(readFail:withError:)]) {
            NSDictionary *userInfo = @{
                NSLocalizedDescriptionKey: @"设备连接失败",
            };
            NSError *error = [NSError errorWithDomain:@"蓝牙设备连接失败" code:ret userInfo:userInfo];
            [self.delegate readFail:peripheral withError:error];
        }
    }
}

#pragma mark - SRReaderDelegate
- (void)idCardInfoJsonStr:(NSString *)jsonStr {
    [_reader closeReader];
    [self setReaderResult:YES];
    NSDate *date = [NSDate date];  // Current date and time
    NSString *formattedDate = [_dateFormatter stringFromDate:date];
    _endTime = formattedDate;
    
    NSDictionary *certInfoDic = [self jsonStrToDic:jsonStr];
    _IDCardModel = [[SRIDCardModel alloc] initWithDic:certInfoDic];
    //合成图片
    [self generatorImg];
    //上传日志
    [self handlerLogInfo];
        
    if ([self.delegate respondsToSelector:@selector(readSuccessWithJsonStr:)]) {
        [self.delegate readSuccessWithJsonStr:jsonStr];
    }
    
    NSDictionary *resultDic = [_logInfo toDictionary];
    if([self.delegate respondsToSelector:@selector(readSuccessWithDic:)]){
        [self.delegate readSuccessWithDic:resultDic];
    }
}

//读卡失败
- (void)SRfailedBack:(CBPeripheral *)peripheral withError:(NSError *)error {
    //设置失败状态
    [self setReaderResult:NO];
    
    NSDate *date = [NSDate date];  // Current date and time
    NSString *formattedDate = [_dateFormatter stringFromDate:date];
    _endTime = formattedDate;

    if ([self.delegate respondsToSelector:@selector(readFail:withError:)]) {
        [self.delegate readFail:peripheral withError:error];
        [_reader closeReader];
    }
    //上传日志
    [self handlerLogInfo];
}

- (void)setReaderResult:(BOOL)success{
    if (success) {
        _opResultCode = @"0";
        _opResultDetail = @"成功";
    }
    else{
        _opResultCode = @"1";
        _opResultDetail = @"失败";
    }
}
//合成身份证图片
- (void)generatorImg{
    _IDCardImg = [SRIDCardGenerator generateIDCardImageWithIDCarModel:_IDCardModel];
    _IDCardBackImg = [SRIDCardGenerator generateIDCardBackImageWithIDCarModel:_IDCardModel];
    _IDCardFrontImg =  [SRIDCardGenerator generateIDCardFrontImageWithIDCarModel:_IDCardModel];
    _IDCardImgBase64 = [self __getBase64:_IDCardImg];
    _IDCardBackImgBase64 = [self __getBase64:_IDCardBackImg];
    _IDCardFrontImgBase64 = [self __getBase64:_IDCardFrontImg];
    NSLog(@"图片合成完毕");
}


- (NSString*)__getBase64:(UIImage *)image{
    NSData *imageData = UIImagePNGRepresentation(image); // 或者 UIImageJPEGRepresentation(image, 1.0)
    NSString *base64String = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return base64String;
}

- (void)recordSdkLogWithParameters:(NSDictionary *)parameters completionBlock:(CompletionHandler)completion{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",_serverAddress,APILog]];
    [self postRequestWithURL:url parameters:parameters completionBlock:completion];
}

- (void)postRequestWithURL:(NSURL *)url
                  parameters:(NSDictionary *)parameters
             completionBlock:(CompletionHandler)completion {
    // 创建请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    
    // 设置请求的 Body
    if (parameters) {
        NSError *error;
        NSData *bodyData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error];
        if (error) {
            if (completion) {
                completion(nil, nil, error);
            }
            return;
        }
        [request setHTTPBody:bodyData];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    }
    
    // 创建会话并发送请求
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSDictionary *jsonResponse;
        if (data) {
                NSError *jsonError;
                jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
                if (jsonError) {
                    NSLog(@"解析错误: %@", jsonError.localizedDescription);
                } else {
                    NSLog(@"返回数据: %@", jsonResponse);
                }
            }
        
        if (completion) {
            completion(jsonResponse, response, error);
        }
    }];
    
    // 启动任务
    [dataTask resume];
}

#pragma mark - 工具

- (NSDictionary *)jsonStrToDic:(NSString *)jsonStr {
    if (jsonStr == nil) {
        return nil;
    }
    jsonStr =[jsonStr stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];//去除字符串里的垃圾字符
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                         options:NSJSONReadingMutableContainers
                         error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
//上传日志
- (void)handlerLogInfo{
    _logInfo.cardPic = _IDCardImgBase64;
    _logInfo.cardFrontPic = _IDCardFrontImgBase64;
    _logInfo.cardBackPic = _IDCardBackImgBase64;
    _logInfo.idPhoto = _IDCardModel.photo;
    _logInfo.validDateEnd = _IDCardModel.expireDate;
    _logInfo.validDateBegin = _IDCardModel.effectDate;
    _logInfo.issuedBy = _IDCardModel.issueOrg;
    _logInfo.idCardNumber = _IDCardModel.idNum;
    _logInfo.address = _IDCardModel.address;
    _logInfo.birthdate = _IDCardModel.birthday;
    _logInfo.nation = _IDCardModel.nation;
    _logInfo.gender = _IDCardModel.gender;
    _logInfo.name = _IDCardModel.name;
    _logInfo.cardTypeName = @"身份证";
    _logInfo.cardTypeCode = @"00";
    _logInfo.phoneNumber = @"";
    _logInfo.devSysVer = [[UIDevice currentDevice] systemVersion];
    _logInfo.devOsName = @"iOS";
    _logInfo.devOsCode = @"1";
    _logInfo.devManu = @"Apple";
    _logInfo.devModel = [[UIDevice currentDevice] model];
    _logInfo.availMemory = @"";
    _logInfo.totalMemory = @"";
    _logInfo.mac = @"";
    _logInfo.terminalId = [[UIDevice currentDevice] identifierForVendor].UUIDString;
    _logInfo.resultTypeDetail = _resultTypeDetail;
    _logInfo.resultTypeCode = _resultTypeCode;
    _logInfo.resultTypeName = _resultTypeName;
    _logInfo.opResultCode = _opResultCode;
    _logInfo.opResultDetail = _opResultDetail;
    _logInfo.startTime = _startTime;
    _logInfo.stopTime = _endTime;
    // 将日期字符串转换为 NSDate 对象
    NSDate *date1 = [_dateFormatter dateFromString:_startTime];
    NSDate *date2 = [_dateFormatter dateFromString:_endTime];
    // 计算两个日期之间的差值
    NSTimeInterval timeInterval = [date2 timeIntervalSinceDate:date1];
    // 计算天数、小时、分钟和秒数
    NSInteger days = timeInterval / (60 * 60 * 24);
    NSInteger hours = (timeInterval / (60 * 60)) - (days * 24);
    NSInteger minutes = (timeInterval / 60) - (days * 24 * 60) - (hours * 60);
    NSInteger seconds = timeInterval - (days * 24 * 60 * 60) - (hours * 60 * 60) - (minutes * 60);
    // 打印结果
    NSLog(@"时间差: %ld天 %ld小时 %ld分钟 %ld秒", (long)days, (long)hours, (long)minutes, (long)seconds);
    _logInfo.timeCost =  [NSString stringWithFormat:@"%ld",seconds];

    _logInfo.opTypeName = @"蓝牙读卡";
    _logInfo.opTypeCode = @"1";
    
    NSMutableDictionary *dic = [_logInfo toDictionary];
    if (_parameter) {
        [dic addEntriesFromDictionary:_parameter];
    }
    [self recordSdkLogWithParameters:dic completionBlock:^(NSDictionary * _Nonnull result, NSURLResponse * _Nonnull response, NSError * _Nonnull error) {
        NSLog(@"%@",result.description);
    }];
}

@end
